package com.niit.chat.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 配置类
 * 处理自动填充字段和乐观锁配置
 */
@Component
public class MyBatisPlusConfig implements MetaObjectHandler {
    /**
     * 自动填充新增记录时的公共字段
     * 
     * @param metaObject 元对象，包含操作实体的信息
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "sendDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
    }
    /**
     * 自动填充更新记录时的公共字段
     * 
     * @param metaObject 元对象，包含操作实体的信息
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
    }
    /**
     * 创建MyBatis Plus拦截器，配置乐观锁功能
     * 
     * @return 配置好的MyBatis Plus拦截器实例
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 启用乐观锁
        return interceptor;
    }

} 